package com.xxgc.location.websocket;

import com.google.gson.Gson;
import com.xxgc.location.po.LocationPO;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;

/**
 * WebSocket /websocket/location
 */

@Component
@ServerEndpoint("/websocket/location")
public class LocationWS {

    //List集合存放Session地址
    private static List<Session> list = new ArrayList<>();

    //WebSocket四种方法
    @OnOpen
    public void onOpen(Session session){
        System.out.println("成功连接");
        list.add(session);
    }
    @OnMessage
    public void onMessage(String message){}
    @OnClose
    public void onClose(Session session){
        System.out.println("连接关闭");
        //需要在list中移除Session
        list.remove(session);
    }

    @OnError
    public void onError(Throwable error,Session session){
        System.out.println("连接出错");
        list.remove(session);
    }

    //写个静态方法 传入PO 把PO变成JSON发送给list内的用户
    public static void sendMessage(LocationPO locationPO) {
        //使用Gson把PO转json
        String json = new Gson().toJson(locationPO);
        for (Session session : list) {
            System.out.println("给前端发送中"+json);
            //发送消息
            session.getAsyncRemote().sendText(json);
        }
    }
}
